<?php
namespace app\shop\controller;

use \think\Controller;
use \think\Db;
class Order extends Base
{


    /**
     * 物料商城:goods
     * page,type
     */
    public function goods(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $where = array();
        $where['ag_status'] = 1;
        $where['ag_type'] = $type;
        $data = Db::table('up_admin_goods')
            ->where($where)
            ->page($page,10)
            ->select();
        if($data){
            foreach ($data as $k=>$v){
                $data[$k]['haveNum'] = 0;
                $have = Db::table('up_shop_car')
                    ->where('car_shop_id',$user_id)
                    ->where('car_goodid',$v['ag_id'])
                    ->field('car_number')
                    ->find();
                if($have){
                    $data[$k]['haveNum'] = $have['car_number'];
                }
            }
        }
        return json_encode(['status'=>200,'msg'=>$data]);
    }
    /**
     * 物料商城的商品分类：goodTypes
     */
    public function goodTypes(){
        $data = Db::table('up_admin_good_type')
            ->select();
        return json_encode(['status'=>200,'msg'=>$data]);
    }
    /**
     * 加入购物车:putGoodInCar
     * ag_id 商品id
     * type  1是加 2是减
     * @return array 返回数组
     */
    public function putGoodInCar(){
        extract(input());
        $auth = $this->checkAll($user_id, $time, $value, $reqKey);
        if ($auth == false) {
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //是不是买了，买了几份（UI上没有，以防万一）
        $buy = Db::table('up_shop_car')
            ->where('car_goodid', $ag_id)
            ->where('car_shop_id', $user_id)
            ->find();
        if($buy){
            if($type == 1){
                $res = Db::table('up_shop_car')
                    ->where('car_goodid', $ag_id)
                    ->where('car_shop_id', $user_id)
                    ->setInc('car_number');
            }else{
                if($buy['car_number'] <= 1){
                    $res = Db::table('up_shop_car')
                        ->where('car_goodid', $ag_id)
                        ->where('car_shop_id', $user_id)
                        ->delete();
                }else{
                    $res = Db::table('up_shop_car')
                        ->where('car_goodid', $ag_id)
                        ->where('car_shop_id', $user_id)
                        ->setDec('car_number');
                }
            }
        }else{
            if($type == 1){
                $data = array();
                $data['car_shop_id'] = $user_id;
                $data['car_goodid'] = $ag_id;
                $data['car_time'] = date('Y-m-d H:i:s');
                $res = Db::table('up_shop_car')->insert($data);
            }else{
                return json_encode(['status'=>0,'msg'=>'不能小于0']);
            }

        }
        if($res){
            return json_encode(['status'=>200,'msg'=>'加入购物车成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'加入购物车失败']);
        }

    }
    /**
     * 我的购物车：myCar
     */
    public function myCar(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $where = array();
        $where['car_shop_id'] = $user_id;
        $where['ag_id'] = array('>',0);
        //1、先分组商家，取得分组数据
        $data = Db::table('up_shop_car')->alias('car')
            ->join('up_admin_goods g','car.car_goodid=g.ag_id','LEFT')
            ->where($where)
            ->order('car_time DESC')
//            ->page($page,10)
            ->select();
        $money = 0;
        $num = 0;
        if($data){
            foreach ($data as $k=>$v){
                $money += $v['ag_money']*$v['car_number'];
                $num += $v['car_number'];
            }
        }
        return json_encode(['status'=>200,'msg'=>$data,'money'=>$money,'num'=>$num]);
    }

    /**
     * 确认订单页：makeOrder
     * 那方支付：type（1是支付宝  2是微信）
     */
    public function makeOrder(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $carids = trim($carids,',');
        $where = array();
        $where['car_shop_id'] = $user_id;
        $where['ag_id'] = array('>',0);
        $where['car_id'] = array('in',$carids);
        //1、先分组商家，取得分组数据
        $data = Db::table('up_shop_car')->alias('car')
            ->join('up_admin_goods g','car.car_goodid=g.ag_id','LEFT')
            ->where($where)
//            ->page($page,10)
            ->select();
        $money = 0;
        $num = 0;
        $jifen = 0;
        $number = date('YmdHis') . rand(1000000,9999999);
        $today = date('Y-m-d');
        $time = date('Y-m-d H:i:s');
        if($data) {
            Db::startTrans();
            try {

                foreach ($data as $k => $v) {
                    $money += $v['ag_money'] * $v['car_number'];
                    $num += $v['car_number'];
                    $jifen += $v['ag_jifen'] * $v['car_number'];
                }
                $order = array();
                $order['so_number'] = $number;
                $order['so_shop_id'] = $user_id;
                $order['so_money'] = $money;
                $order['so_num'] = $num;
                $order['so_time'] = $time;
                $order['so_jifen'] = $jifen;
                $order['so_type'] = $type;
                $orderid = Db::table('up_shop_order')->insertGetId($order);
                foreach ($data as $k => $v) {
                    //------------减库存
//                    if($v['ag_stock'] != -1){
//                        if($v['ag_stock'] >= $v['car_number']){
//                            Db::table('up_admin_goods')
//                                ->where('ag_id',$v['ag_id'])
//                                ->setDec('ag_stock',$v['car_number']);
//                        }else{
//                            Db::rollback();
//                            return json_encode(['status'=>0,'msg'=>'库存不足']);
//                        }
//
//                    }
                    //------------------
                    $info = array();
                    $info['oi_so_id'] = $orderid;
                    $info['oi_good_id'] = $v['ag_id'];
                    $info['oi_shop_id'] = $user_id;
                    $info['oi_good_money'] = $v['ag_money'];
                    $info['oi_num'] = $v['car_number'];
                    $info['oi_jifen'] = $v['ag_jifen'];
                    $info['oi_good_name'] = $v['ag_name'];
                    $info['oi_good_thumb'] = $v['ag_thumb'];
                    Db::table('up_shop_order_info')->insert($info);
                    Db::table('up_shop_car')->where('car_id', $v['car_id'])->delete();
                }
                Db::commit();
                if ($type == 1) {
                    $respont = $this->getParamOrder($number, 0.01);//$money
                    return json_encode($respont);
                } else {
                    $orderWx = array();
                    $orderWx['body'] = '红集';
                    $orderWx['total_fee'] = 1;
                    $orderWx['out_trade_no'] = $number;
                    $orderWx['product_id'] = '';
                    $orderWx['trade_type'] = 'APP';
                    $respont = $this->WeChatPayReady($orderWx,'http://mww5.xuanwumobile.com/shop/Order/huidiaoWx');
                    return json_encode(['status' => 200, 'msgsss' => $respont]);
                }
            } catch (\Exception $e) {
                Db::rollback();
                return json_encode(['status' => 0, 'msgsss' => '生成订单失败，请联系管理员']);
            }
        }else{
            return json_encode(['status' => 0, 'msgsss' => '购物车出错']);
        }
    }
    /**
     * 单独为取消订单做的支付：onlyPay
     * @return string
     * $so_id,$type
     */
    public function onlyPay()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $order = array();
        $number = date('YmdHis') . rand(1000000, 9999999);
        $order['so_number'] = $number;
        $order['so_type'] = $type;
        $pay = Db::table('up_shop_order')->where('so_id', $so_id)->value('so_money');
        $res = Db::table('up_shop_order')->where('so_id', $so_id)->update($order);
        if($res){
            if ($type == 1) {
                $respont = $this->getParamOrder($number, 0.01);//$money
                return json_encode($respont);
            } else {
                $orderWx = array();
                $orderWx['body'] = '红集';
                $orderWx['total_fee'] = 1;
                $orderWx['out_trade_no'] = $number;
                $orderWx['product_id'] = '';
                $orderWx['trade_type'] = 'APP';
                $respont = $this->WeChatPayReady($orderWx,'http://mww5.xuanwumobile.com/shop/Order/huidiaoWx');
                return json_encode(['status' => 200, 'msgsss' => $respont]);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>'订单号更改失败']);
        }

    }
    /**
     * @return string
     */
    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo){
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED'){
                $number = $getInfo['out_trade_no'];
                Db::startTrans();
                try{
                    $order = Db::table('up_shop_order')->where('so_number',$number)->find();
                    //先加商户积分
                    Db::table('up_shops')->where('s_id',$order['so_shop_id'])
                        ->setInc('s_integral',$order['so_jifen']);
                    $shop = Db::table('up_shops')->where('s_id',$order['so_shop_id'])->find();
                    if($shop['s_status'] == 2){
                        if($shop['s_integral'] >= 0){
                            Db::table('up_shops')->where('s_id',$order['so_shop_id'])
                                ->update(['s_status'=>1]);
                        }
                    }
                    //再改订单状态
                    $update = array();
                    $update['so_status'] = 2;
                    $update['so_paytime'] = $getInfo['gmt_payment'];
                    $update['so_paydate'] = substr($getInfo['gmt_payment'],0,10);
                    $update['so_back_transaction_id'] = $getInfo['trade_no'];
                    Db::table('up_shop_order')->where('so_number',$number)->update($update);
                    //通知
                    allInNotice('积分增加通知','购买宣传物料获得积分'.$order['so_jifen'],$order['so_shop_id']);
                    allInJifen('购买宣传物料',1,$order['so_jifen'],$order['so_shop_id']);
                    Db::commit();
                    die('success');
                }catch (\Exception $e) {
                    Db::rollback();
                    return 'error';
                }
            }
        }
    }
    public function huidiaoWx()
    {
        $xml=file_get_contents('php://input', 'r');
        $getInfo=$this->toArray($xml);
        $data_sign=$getInfo['sign'];
        unset($getInfo['sign']);
        $sign = $this->makeSign($getInfo);
        // 判断签名是否正确  判断支付状态
        if ($sign === $data_sign && $getInfo['return_code'] == 'SUCCESS' && $getInfo['result_code'] == 'SUCCESS') {
            Db::startTrans();
            try{
                $number = $getInfo['out_trade_no'];
                $transaction_id = $getInfo['transaction_id'];
                $paytime = $this->getDateBytimeDate("{$getInfo['time_end']}");
                $order = Db::table('up_shop_order')->where('so_number',$number)->find();
                //先加商户积分
                Db::table('up_shops')->where('s_id',$order['so_shop_id'])
                    ->setInc('s_integral',$order['so_jifen']);
                $shop = Db::table('up_shops')->where('s_id',$order['so_shop_id'])->find();
                if($shop['s_status'] == 2){
                    if($shop['s_integral'] >= 0){
                        Db::table('up_shops')->where('s_id',$order['so_shop_id'])
                            ->update(['s_status'=>1]);
                    }
                }
                //再改订单状态
                $update = array();
                $update['so_status'] = 2;
                $update['so_paytime'] = $paytime;
                $update['so_paydate'] = substr($paytime,0,10);
                $update['so_back_transaction_id'] = $transaction_id;
                Db::table('up_shop_order')->where('so_number',$number)->update($update);
                //通知
                allInNotice('积分增加通知','购买宣传物料获得积分'.$order['so_jifen'],$order['so_shop_id']);
                allInJifen('购买宣传物料',1,$order['so_jifen'],$order['so_shop_id']);
                Db::commit();
                $result = $getInfo;
            }catch (\Exception $e) {
                Db::rollback();
                $result = false;
            }
        }else{
            $result = false;
        }
        // 返回状态给微信服务器----------------
        if ($result) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
        exit();
        return $result;
    }

    /**
     *  TODO 将我的未支付的订单删掉并且库存改回去
     * param $user_id
     */
    public function updateOneToDel($user_id)
    {
        $today = date('Y-m-d H:i:s');
        $deltime = date("Y-m-d H:i:s",(strtotime("{$today}")-1800));
        $order = Db::table('up_shop_order')
            ->where('so_shop_id',$user_id)
            ->where('so_status',1)
            ->where('so_time','<=',$deltime)
            ->column('so_id');
        if($order){
            Db::table('up_shop_order')
                ->where('so_id','in',$order)
                ->delete();
            Db::table('up_shop_order_info')->where('oi_so_id',$order)->delete();
        }
        return true;
    }
    /**
     * 我的不同类型的订单：myOrder
     * type(0全部  1待支付  2待收货  3是已收货),$page
     * @return string
     */
    public function myOrder()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $this->updateOneToDel($user_id);
        $where = array();
        $where['so_shop_id'] = $user_id;
        if($type > 0){
            $where['so_status'] = $type;
        }
        $order = Db::table('up_shop_order')
            ->where($where)
            ->order('so_time DESC')
            ->page($page,10)
            ->select();
        if($order){
            foreach ($order as $k=>$v){
                $order[$k]['goods'] = Db::table('up_shop_order_info')
                    ->where('oi_so_id',$v['so_id'])
                    ->select();
            }
        }
        $time = time();
        return json_encode(['status'=>200,'msg'=>$order,'time'=>$time]);
    }
    /**
     * 订单详情：myOrderInfo
     * order_id
     * @return string
     */
    public function myOrderInfo()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $where = array();
        $where['so_id'] = $so_id;
        $order = Db::table('up_shop_order')->alias('o')
            ->join('up_shops s','o.so_shop_id=s.s_id','LEFT')
            ->where($where)
            ->field('o.*,s.s_id,s.s_name,s_phone,s_thumb,s_address')
            ->find();
        $goods = Db::table('up_shop_order_info')
            ->where('oi_so_id',$so_id)
            ->select();
        $time = time();
        return json_encode(['status'=>200,'order'=>$order,'goods'=>$goods,'time'=>$time]);
    }
    /**
     * 取消订单:cancelOrder
     * order_id
     * @return string
     */
    public function cancelOrder()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        Db::startTrans();
        try{
            Db::table('up_shop_order')->where('so_id',$so_id)->delete();
            Db::table('up_shop_order_info')->where('oi_so_id',$so_id)->delete();
            Db::commit();
            return json_encode(['status'=>200,'msg'=>'取消成功']);
        }catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }
    }
    /**
     * 确认收货：getMyOrder
     * order_id
     * @return string
     */
    public function getMyOrder()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $res = Db::table('up_shop_order')->where('so_id',$so_id)->update(['so_status'=>3,'so_send_status'=>3]);
        if($res){
            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }
    }
    /**
     * 申请退款：tuikuan
     * @return string
     */
    public function tuikuan()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $res = Db::table('up_shop_order')
            ->where('so_id',$so_id)
            ->update(['so_in_out'=>2]);
        if($res){
            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }
    }
}